<script setup lang="ts">
import Content from '@/components/Content/index.vue'
import ContentTitle from '@/components/ContentTitle/index.vue'
import APIEarnings from '@/api/earnings'
import { useAuth } from '@/stores/index'
import SelfPagination from '@/components/SelfPagination/index.vue'
import { ElMessage, type FormInstance, type FormRules, ElLoading } from 'element-plus'
import APIInformation from '@/api/information'

const { info } = storeToRefs(useAuth())
const { getInfo } = useAuth()
const list = ref<any>([])
const loading = shallowRef<boolean>(false)
const total = shallowRef<number>(0)

const queryParams = ref<PageQuery>({
    page: 1,
    limit: 8
})

function getList() {
    loading.value = true
    APIEarnings.getProfit(queryParams.value).then(({ data, total: count }) => {
        list.value = data
        total.value = count
    }).finally(() => {
        loading.value = false
    })
} getList()

const dialogVisible = shallowRef<boolean>(false)
const formData = ref<any>({
    withdrawal_port: '2'
})

function onBeforeClose() {
    formData.value = {
        withdrawal_port: '2'
    }
    dialogVisible.value = false
}

const ruleFormRef = shallowRef<FormInstance>()

const rules = reactive<FormRules<any>>({
    bank_name: [{
        required: true,
        message: '请进行绑定',
        trigger: 'blur'
    }],
    withdrawal_port: [{
        required: true,
        message: '请选择提现端口',
        trigger: 'blur'
    }],
    amount: [{
        required: true,
        message: '请输入提现金额',
        trigger: 'blur'
    }, {
        pattern: /^\d+$/,
        message: '只能输入数字',
        trigger: 'blur'
    }, {
        validator: (rule: any, value: any, callback: any) => {
            if (Number(value) > Number(info.value.shop_wallet)) {
                callback(new Error('提现金额大于可提金额'))
            }
            callback()
        },
        trigger: 'blur'
    }]
})

const protocol = shallowRef<string>('')

function getProtocol() {
    APIEarnings.getProtocol().then(({ data }) => {
        protocol.value = data.content
    })
} getProtocol()

const innterVisible = shallowRef<boolean>(false)

const timerNumber = shallowRef<number>(10)

let timer: number | null = null

const isW = shallowRef<boolean>(false)

function handleReplenishment() {
    innterVisible.value = true

    timer = setInterval(() => {
        if (timerNumber.value > 0) {
            timerNumber.value -= 1
        } else {
            if (timer) {
                clearInterval(timer)
                timer = null
                isW.value = true
            }
        }
    }, 1000)
}


const consent = shallowRef<any>()

function handleW() {
    if (!consent.value) return ElMessage.error('未勾选我已阅读协议全部内容，同意协议内容且签署协议')
    const loading = ElLoading.service({ lock: true })
    APIEarnings.setProtocolLog().then(() => {
        ElMessage.success('操作成功')
        getInfo()
        innterVisible.value = false
    }).finally(() => {
        loading.close()
    })
}


function onBeforeInnterClose() {
    timerNumber.value = 10
    isW.value = false
    consent.value = undefined
    if (timer) {
        clearInterval(timer)
        timer = null
    }

    innterVisible.value = false

}

const bindAlipayVisible = shallowRef<boolean>(false)

const bindAlipayFormData = ref<any>({})

const bindAlipayFormRef = shallowRef<FormInstance>()

const bindAlipayRules = reactive({
    real_name: [{
        required: true,
        message: '请输入用户名',
        trigger: 'blur'
    }],
    alipay: [{
        required: true,
        message: '请输入支付宝账号',
        trigger: 'blur'
    }]
})

watch(() => info.value.alipay, (newValue) => {
    bindAlipayFormData.value.alipay = newValue
}, { immediate: true })



function submitBindAlipayFormData() {
    bindAlipayFormRef.value?.validate((valid) => {
        if (valid) {
            const loading = ElLoading.service({ lock: true })
            APIInformation.changePersonal({
                ...bindAlipayFormData.value
            }).then(({ msg }) => {
                ElMessage.success(msg)
                bindAlipayFormData.value = {}
                bindAlipayVisible.value = false
                getInfo()
            }).finally(() => {
                loading.close()
            })
        }
    })
}


const bindBankCardVisible = shallowRef<boolean>(false)

const bindBankCardFormData = ref<any>({})

watch(() => info.value.brank_code, (newValue) => {
    bindBankCardFormData.value.brank_code = newValue
}, { immediate: true })

watch(() => info.value.brank_name, (newValue) => {
    bindBankCardFormData.value.brank_name = newValue
}, { immediate: true })


const bindBankCardRules = reactive({
    real_name: [{
        required: true,
        message: '请输入用户名',
        trigger: 'blur'
    }],
    brank_name: [{
        required: true,
        message: '请输入开户名称',
        trigger: 'blur'
    }],
    brank_code: [{
        required: true,
        message: '请输入开户账号',
        trigger: 'blur'
    }]
})

const bindBankCardRef = shallowRef<FormInstance>()

function submitBindBankCardFormData() {
    bindBankCardRef.value?.validate((valid) => {
        if (valid) {
            const loading = ElLoading.service({ lock: true })
            APIInformation.changePersonal({
                ...bindBankCardFormData.value
            }).then(({ msg }) => {
                ElMessage.success(msg)
                bindBankCardFormData.value = {}
                bindBankCardVisible.value = false
                getInfo()
            }).finally(() => {
                loading.close()
            })
        }
    })
}

function submitForm() {
    if (info.value.is_protocol == 0) return ElMessage.error('未签约签署协议')

    if (formData.value.withdrawal_port == 1) {
        formData.value.bank_name = info.value.alipay
    } else if (formData.value.withdrawal_port == 2) {
        formData.value.bank_name = info.value.brank_code
    }

    ruleFormRef.value?.validate((valid) => {
        if (valid) {
            const loading = ElLoading.service({ lock: true })
            APIEarnings.withdrawal(formData.value).then(() => {
                ElMessage.success('提现成功')
                onBeforeClose()
                getList()
                getInfo()
            }).finally(() => {
                loading.close()
            })
        }
    })
}

</script>

<template>
    <div class="earnings">
        <Content class="content">
            <ContentTitle title="店铺盈利（收益）" content="店铺盈利包含自有产品销售、搬运产品、打赏的盈利（收益）；" />
            <div class="item-1">
                <div>
                    <p>{{ info.shop_wallet ? Number(info.shop_wallet) : 0 }}</p>
                    <p>可用金额</p>
                </div>
                <button type="button" @click="dialogVisible = true">提现</button>
            </div>
        </Content>
        <ContentTitle title="盈利提现" content="提现/支出的具体明细；" />
        <el-table class="list" :data="list"
            style="margin: 0 auto; margin-top: 30px; width: 99.99%; margin-bottom: 30px;"
            :header-cell-style="{ background: '#f5f7fa', color: '#606266' }">
            <el-table-column prop="create_time" label="提现时间" />
            <el-table-column label="类型">提现</el-table-column>
            <el-table-column prop="amount" label="金额" />
            <el-table-column label="提现端口" v-slot="{ row }">
                <span v-if="row.withdrawal_port == 1">支付宝</span>
                <span v-if="row.withdrawal_port == 2">银行卡</span>
                <span v-if="row.withdrawal_port == 3">微信</span>
            </el-table-column>
            <el-table-column prop="bank_name" label="提现账号" />
            <el-table-column label="提现状态" v-slot="{ row }">
                <span v-if="row.withdrawal_status == 0">待处理</span>
                <span v-if="row.withdrawal_status == 1">已处理</span>
                <span v-if="row.withdrawal_status == 2">拒绝处理</span>
            </el-table-column>
        </el-table>
        <SelfPagination style="margin-top: 50px;" :total="total" v-model:current-page="queryParams.page"
            :page-size="queryParams.limit" @get-list="getList" />
        <el-dialog class="dialog-message" title="提现申请" v-model="dialogVisible" width="800" destroy-on-close
            :before-close="onBeforeClose" :show-close="false">
            <template #header>
                <DialogClose title="提现申请" @close="onBeforeClose" />
            </template>
            <el-dialog v-model="innterVisible" title="提现协议签署" width="600" :before-close="onBeforeInnterClose"
                :show-close="false">
                <template #header>
                    <DialogClose title="提现协议签署" @close="onBeforeInnterClose" />
                </template>
                <div class="replenishment">
                    <span v-html="protocol"></span>
                </div>
                <el-checkbox
                    style="margin: 0 auto; margin-bottom: 10px; display: block; display: flex; justify-content: center; font-family: 'SOURCEHANSANSCN-LIGHT';"
                    v-model="consent" label="我已阅读协议全部内容，同意协议内容且签署协议" />
                <el-button color="#0790C3" style="margin: 0 auto; display: block;" @click="handleW" :disabled="!isW">
                    <span v-if="!isW">{{ timerNumber }}s秒后即可同意并签署</span>
                    <span v-else>同意并签署</span>
                </el-button>
            </el-dialog>
            <el-dialog v-model="bindAlipayVisible" title="绑定支付宝" width="600" :show-close="false">
                <template #header>
                    <DialogClose title="绑定支付宝" @close="bindAlipayVisible = false" />
                </template>
                <el-form ref="bindAlipayFormRef" style="width: 100%;" :model="bindAlipayFormData" label-width="auto"
                    :rules="bindAlipayRules">
                    <el-form-item label="用户名" prop="real_name">
                        <el-input v-model="bindAlipayFormData.real_name" placeholder="请输入用户名"></el-input>
                    </el-form-item>
                    <el-form-item label="支付宝账号" prop="alipay">
                        <el-input v-model="bindAlipayFormData.alipay" placeholder="请输入支付宝账号"></el-input>
                    </el-form-item>
                </el-form>
                <button type="button" class="accomplish" @click="submitBindAlipayFormData">提交</button>
            </el-dialog>
            <el-dialog v-model="bindBankCardVisible" title="绑定银行卡" width="600" :show-close="false">
                <template #header>
                    <DialogClose title="绑定银行卡" @close="bindBankCardVisible = false" />
                </template>
                <el-form ref="bindBankCardRef" style="width: 100%;" :model="bindBankCardFormData" label-width="auto"
                    :rules="bindBankCardRules">
                    <el-form-item label="用户名" prop="real_name">
                        <el-input v-model="bindBankCardFormData.real_name" placeholder="请输入用户名"></el-input>
                    </el-form-item>
                    <el-form-item label="开户名称" prop="brank_name">
                        <el-input v-model="bindBankCardFormData.brank_name" placeholder="请输入开户名称"></el-input>
                    </el-form-item>
                    <el-form-item label="开户账号" prop="brank_code">
                        <el-input v-model="bindBankCardFormData.brank_code" placeholder="请输入开户账号"></el-input>
                    </el-form-item>
                </el-form>
                <button type="button" class="accomplish" @click="submitBindBankCardFormData">提交</button>
            </el-dialog>

            <div class="cash-withdrawal">可提金额：￥ {{ Number(info.shop_wallet) }}</div>
            <el-form ref="ruleFormRef" style="max-width: 600px" :model="formData" :rules="rules" label-width="auto"
                class="demo-ruleForm">
                <el-form-item label="提现端口" prop="withdrawal_port">
                    <el-radio-group v-model="formData.withdrawal_port">
                        <el-radio value="2">银行卡</el-radio>
                        <el-radio value="1">支付宝</el-radio>
                        <el-radio value="3" disabled>微信</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="签署协议">
                    <el-text type="primary" v-if="info.is_protocol == 1">已签约</el-text>
                    <el-text style="cursor: pointer;" type="danger" v-else-if="info.is_protocol == 0"
                        @click="handleReplenishment">补签</el-text>
                </el-form-item>
                <el-form-item label="绑定支付宝" prop="bank_name" v-if="formData.withdrawal_port == 1">
                    <div class="alipay">
                        <div style="margin-right: 10px;" v-if="info.is_alipay == 1">{{ info.alipay }}</div>
                        <el-text type="primary" style="cursor: pointer;" v-if="info.is_alipay == 1"
                            @click="bindAlipayVisible = true">修改</el-text>
                        <el-text type="primary" style="cursor: pointer;" v-else
                            @click="bindAlipayVisible = true">绑定</el-text>
                    </div>
                </el-form-item>
                <el-form-item label="绑定银行卡" prop="bank_name" v-if="formData.withdrawal_port == 2">
                    <div class="alipay">
                        <div style="margin-right: 10px;" v-if="info.is_brank == 1">{{ info.brank_name }}-{{
                            info.brank_code }}</div>
                        <el-text type="primary" style="cursor: pointer;" v-if="info.is_brank == 1"
                            @click="bindBankCardVisible = true">修改</el-text>
                        <el-text type="primary" style="cursor: pointer;" v-else
                            @click="bindBankCardVisible = true">绑定</el-text>
                    </div>
                </el-form-item>
                <el-form-item label="提现金额" prop="amount">
                    <el-input v-model="formData.amount" />
                </el-form-item>
            </el-form>
            <button type="button" class="accomplish" @click="submitForm">提交</button>
        </el-dialog>
    </div>
</template>

<style lang="scss">
.earnings {
    .list {
        .el-table__row {
            font-family: 'SOURCEHANSANSCN-EXTRALIGHT';
        }

        .cell {
            font-family: 'SOURCEHANSANSCN-EXTRALIGHT';
        }
    }
}
</style>

<style lang="scss" scoped>
.alipay {
    display: flex;


    button {
        display: block;
        width: 80px;
        height: 32px;
        border-radius: 5px;
        background-color: rgb(15, 64, 245);
        color: rgb(255, 255, 255);
        font-size: 14px;
        border: none;
        cursor: pointer;
        margin-left: 20px;
    }
}

.accomplish {
    display: block;
    width: 200px;
    height: 40px;
    border-radius: 5px;
    background-color: rgba(15, 64, 245, 1);
    color: rgba(255, 255, 255, 1);
    font-size: 14px;
    border: none;
    cursor: pointer;
    margin: 0 auto;
}

.dialog-message {

    .consent {
        width: 150px;
        height: 50px;
        background-color: #0790C3;
        border: none;
        color: #ffffff;
        border-radius: 5px;
        display: block;
        margin: 0 auto;
        cursor: pointer;
    }

    .replenishment {
        height: 400px;
        overflow-y: auto;
    }

    .cash-withdrawal {
        font-size: 14px;
        margin-left: 25px;
        margin-bottom: 10px;
    }
}


.earnings {
    width: 99%;
    margin: 0 auto;

    .content {
        margin-bottom: 30px;
        position: relative;
    }


    .item-1 {
        display: flex;
        justify-content: center;
        gap: 0 30px;
        padding-top: 30px;
        padding-bottom: 20px;

        button {
            width: 313px;
            height: 72px;
            line-height: 72px;
            border-radius: 5px;
            background-color: #F91414;
            color: #ffffff;
            font-size: 28px;
            border: none;
            cursor: pointer;
        }

        div {
            width: 673px;
            height: 177px;
            border-radius: 10px;
            background-color: rgba(238, 238, 239, 1);
            overflow: hidden;

            p {
                text-align: center;

                &:first-child {
                    color: #F91414;
                    font-size: 72px;
                    margin-top: 35px;
                    font-weight: 700;
                }

                &:last-child {
                    color: #797979;
                    font-size: 16px;
                    margin-top: 10px;
                    font-family: 'SOURCEHANSANSCN-EXTRALIGHT';
                }
            }
        }
    }
}
</style>

<style lang="scss">
.bank-name {
    .el-input-group__append {
        cursor: pointer;
        background-color: #3E82F4;
        color: #ffffff;
        border-color: #3E82F4;
        box-shadow: none;
    }

}
</style>